package com.maimao.order.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.maimao.api.order.OrderApi;
import com.maimao.core.model.auth.AuthUser;
import com.maimao.core.model.resp.PageResult;
import com.maimao.core.model.resp.Result;
import com.maimao.core.utils.DateUtils;
import com.maimao.model.kill.dto.KillDto;
import com.maimao.model.order.Order;
import com.maimao.model.order.OrderGoods;
import com.maimao.model.order.input.CommentStatusUpdateInput;
import com.maimao.model.order.input.CommitOrder;
import com.maimao.model.order.input.OrderSearchInput;
import com.maimao.model.order.vo.ExportOrderEntity;
import com.maimao.model.order.vo.OrderShopEx;
import com.maimao.model.user.Shop;
import com.maimao.order.client.ShopClient;
import com.maimao.order.controller.base.BaseController;
import com.maimao.order.mapper.KillSuccessMapper;
import com.maimao.order.rabbit.RabbitSender;
import com.maimao.order.serivce.OrderKillService;
import com.maimao.order.serivce.OrderService;
import com.maimao.utils.excel.ExcelUtil;
import com.maimao.utils.excel.convert.CommonBoolConvert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static com.maimao.core.constant.AuthKey.COMPANY;
import static com.maimao.core.constant.AuthKey.MEMBER;
import static com.maimao.core.constant.Constants.UNDER_LINE;
import static com.maimao.order.config.RabbitProperties.PAY_EXPIRE;

/**
 * 普通订单采用下单减库存 但给定付款有效期 即半小时内付款 否则订单自动取消 返还库存。 秒杀订单采用付款减库存
 *
 * @author MaoLin Wang
 * @date 2021/1/15 2:22 下午
 */
@Slf4j
@RestController
public class OrderController extends BaseController implements OrderApi {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RabbitSender rabbitSender;

    @Autowired
    private ShopClient shopClient;

    @Autowired
    private KillSuccessMapper killSuccessMapper;

    @Autowired
    private OrderKillService orderKillService;


    @GetMapping("/test")
    public void test() throws IOException {
        Order order = orderService.queryOrder(5094208757864693762L);
        ExcelUtil.builder().setMustParams(Order.class, Lists.newArrayList(order), "aa", getResponse()).export();
        ;
    }

    /**
     * 普通订单提交
     */
    @Override
    @PostMapping("/submit")
    public Result<?> commitOrder(@Valid @RequestBody CommitOrder commitOrder, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return entityInvalid(bindingResult);
        }
        log.info("订单信息：{}", commitOrder);
        AuthUser authUser = checkAndGetAuthUser();
        return orderService.submit(commitOrder, authUser.getId2Long());
    }

    /**
     * 提交秒杀订单
     */
    @PostMapping("/client/submitKillOrder")
    public Result killOrder(@RequestBody KillDto dto) {
        if (dto == null || dto.getUserId() == null || dto.getKillId() == null || dto.getOrderId() == null) {
            return Result.notValid();
        }
        if (killSuccessMapper.countKilled(dto.getKillId(), dto.getUserId()) > 0) {
            return Result.notValid("已经秒杀过");
        }
        orderKillService.killOrder(dto.getUserId(), dto.getKillId(), dto.getOrderId());
        return Result.ok("commit success");
    }

    @PostMapping("/cancel")
    public Result<?> cancel() {
//        rabbitSender.sendOrderCommitMessage(Long.valueOf("5069661645375578114"));
//        orderService.cancelOrder(Long.valueOf("5069137831164059648"), 1L);
        return Result.ok();
    }

    /**
     * 查询订单状态
     */
    @Override
    @GetMapping("/check-order/{orderId}")
    public Result<?> checkOrder(@PathVariable("orderId") String orderId) {

        Map<String, Object> res = Maps.newHashMapWithExpectedSize(2);
        res.put("status", -1);

        Long orderIdL = null;
        if (StringUtils.isEmpty(orderId) || (orderIdL = Long.valueOf(orderId)) == null || orderIdL <= 0) {
            //无效订单
            return Result.okData(res);
        }
        Order order = orderService.queryOrderStatus(orderIdL);
        if (order == null) {
            return Result.okData(res);
        }
        AuthUser authUser = checkAndGetAuthUser();
        if (!order.getUserId().equals(authUser.getId2Long())) {
            return Result.notValid("非法请求");
        }
        Integer payExpireMill = Integer.valueOf(PAY_EXPIRE);
        int payExpireMin = payExpireMill / 60000;
        // 避免由于RabbitMQ过期取消订单失败，这里在查询的时候进一步判断是否过期，如果过期则取消
        if (order.getCreateTime().plusMinutes(payExpireMin).compareTo(DateUtils.now()) < 0) {
            //订单已经过期
            orderService.cancelOrder(orderIdL, authUser.getId2Long());
            order = orderService.queryOrderStatus(orderIdL);
        }

        res.put("status", order.getStatus());
        res.put("createTime", order.getCreateTime());
        return Result.okData(res);
    }

    /**
     * 付款
     *
     * @param orderData key orderId value 订单号
     * @return
     */
    @Override
    @PostMapping("/pay")
    public Result<?> pay(@RequestBody Map<String, String> orderData) {

        if (orderData == null) {
            return Result.notValid("无效订单");
        }
        String orderIdStr = orderData.get("orderId");
        Long orderId = null;
        if (StringUtils.isEmpty(orderIdStr) || (orderId = Long.valueOf(orderIdStr)) == null || orderId <= 0) {
            return Result.notValid("无效订单");
        }
        boolean payRes = orderService.pay(orderId, checkAndGetAuthUser().getId2Long());
        return payRes ? Result.ok("付款成功") : Result.fail("支付失败，订单可能已超过支付时间");
    }

    /**
     * 当前用户订单查询
     */
    @PostMapping("/user-order")
    @Override
    public Result<?> userOrderList(@RequestBody OrderSearchInput input,
                                                         @RequestParam(value = "page", defaultValue = "1") Integer page,
                                                         @RequestParam(value = "size", defaultValue = "5") Integer size) {
        AuthUser authUser = checkAndGetAuthUser();
        input.setDeleted(0);
        PageResult<OrderShopEx> res = orderService.queryUserOrderList(input, page, size, authUser.getId2Long());
        return Result.okData(res);
    }

    /**
     * 当前用户（卖家）订单查询
     */
    @PostMapping("/shop-order")
    @Override
    public Result<?> shopOrderList(@RequestBody OrderSearchInput input,
                                                         @RequestParam(value = "page", defaultValue = "1") Integer page,
                                                         @RequestParam(value = "size", defaultValue = "5") Integer size) {
        AuthUser authUser = checkAndGetAuthUser();
        Result x = setShopId(input, authUser);
        if (x != null) return x;
        PageResult<OrderShopEx> res = orderService.queryUserOrderList(input, page, size, null);
        return Result.okData(res);
    }


    /**
     * 删除订单
     */
    @Override
    @PostMapping("/delete")
    public Result<?> delete(@RequestBody Map<String, Long> data) {
        if (data == null || data.get("orderId") == null) {
            return Result.notValid();
        }
        Long orderId = data.get("orderId");
        if (orderId <= 0) {
            return Result.notValid();
        }
        AuthUser authUser = checkAndGetAuthUser();
        return orderService.delete(orderId, authUser.getId2Long());
    }

    /**
     * 发货
     *
     * @param data key:id / orderShopId
     * @return
     */
    @Override
    @PostMapping("/delivery")
    public Result<?> delivery(@RequestBody Map<String, Long> data) {
        //orderGoodsId
        Long id = null;
        Long orderShopId = null;
        Long orderId = null;
        if (data == null || (id = data.get("id")) == null || id <= 0 || (orderShopId = data.get("orderShopId")) == null || orderShopId <= 0 || (orderId = data.get("orderId")) == null || orderId <= 0) {
            return Result.notValid();
        }
        Result res = orderService.delivery(id, orderShopId, orderId);
        if (res.isFlag()) {
            return Result.ok("发货成功");
        } else {
            return res;
        }
    }

    /**
     * 确认收货
     *
     * @param data key:id / orderShopId
     * @return
     */
    @Override
    @PostMapping("/check-receive")
    public Result<?> receiveGoods(@RequestBody Map<String, Long> data) {
        Long id = null;
        Long orderShopId = null;
        if (data == null || (id = data.get("id")) == null || id <= 0 || (orderShopId = data.get("orderShopId")) == null || orderShopId <= 0) {
            return Result.notValid();
        }
        orderService.receiveGoods(id, orderShopId);
        return Result.ok("收货成功");
    }

    /**
     * 更新订单评论状态
     *
     * @param input
     * @return
     */
    @Override
    @PostMapping("/update-comment")
    public Result<?> updateComment(@RequestBody CommentStatusUpdateInput input) {
        if (input == null || input.getOrderId() == null || input.getOrderId() <= 0 || input.getSkuId() == null || input.getSkuId() <= 0) {
            return Result.notValid();
        }
        orderService.updateCommentStatus(input);
        return Result.ok();
    }

    /**
     * 查询评论状态
     *
     * @param input
     * @return
     */
    @PostMapping("/comment-status")
    @Override
    public Result<?> commentStatus(@RequestBody CommentStatusUpdateInput input) {
        if (input == null || input.getOrderId() == null || input.getOrderId() <= 0 || input.getSkuId() == null || input.getSkuId() <= 0) {
            return Result.notValid();
        }
        OrderGoods res = orderService.queryCommentStatus(input);
        return Result.okData(res.getComment());
    }


    private Result setShopId(@RequestBody OrderSearchInput input, AuthUser authUser) {
        Result<Shop> shopRes = null;
        if (authUser.getRole().equals(COMPANY)) {
            //企业用户
            shopRes = shopClient.findShopByOwner(authUser.getId2Long(), 1);
        } else if (authUser.getRole().equals(MEMBER)) {
            //普通用户
            shopRes = shopClient.findShopByOwner(authUser.getId2Long(), 0);
        } else {
            return Result.notValid("非法用户");
        }
        if (shopRes == null || shopRes.getData() == null || shopRes.getData().getId() == null || shopRes.getData().getId() <= 0) {
            return Result.notValid("您尚未开通店铺");
        }
        input.setShopId(shopRes.getData().getId());
        return null;
    }

}
